/**
 * uni-app上拉加载和下拉刷新混合(支持搜索功能)
 * @author maybe
 */
import {
    jj, isnull
} from '@/common/lib/fun.js'
export default {
    data() {
        return {
            id: '',
            allloading: false, // 是否加载数据
            allfinished: false, // 是否加载完成
            alllist: [], // 数据列表
            allpage: 0, // 由于分页一般页面要+1，所以为了方便分页查询，这里初始设置页码为0
            allsize: 5, // 每页显示的条数
            alltotal: 0, // 数据总条数
            allsearch: {}, // 搜索对象
            tempallsearch: {} // 提供给混合初始化搜索对象
        };
    },
    async onLoad(option) {
        var t = this
        console.log(option);
        if (isnull(option.id) == '' || isnull(option.type) == '') {

        } else {
            console.log('666');
            t.id = option.id
        }
        // 拷贝搜索初始化对象属性和数据
        this.tempallsearch = _deepClone(this.allsearch);
        console.log(this.tempallsearch)
        // 查询列表
        await this._getalllistFactory();
    },
    // 下拉刷新
    async onPullDownRefresh() {
        this._initallpageData();
        this._resetallsearch();
        await this._getalllistFactory();
        uni.stopPullDownRefresh();
    },
    // 上拉加载
    async onReachBottom() {
        console.log('上拉加载');
        // this.allpage = 0
        // this.allsize = 5
        // this.alltotal = 0
        // this.alllist = []
        this._getalllistFactory();
    },
    // 所有混合的方法均已'_'开头
    methods: {
        async _allsearchData() {
            this._initallpageData();
            await this._getalllistFactory();
        },
        // 重置搜索
        _resetallsearch() {
            this.allsearch = _deepClone(this.tempallsearch)
            // console.log('重置搜索完成', this.allsearch)
        },
        // 初始化页面的数据
        _initallpageData(allsize) {
            this.allfinished = false;
            this.allpage = 0;
            this.alllist = [];
            this.allsize = allsize || 5;
            this.alltotal = 0;
        },
        async _getalllistFactory() {
            // 如果已经全部加载完成直接终止执行
            if (this.allfinished) return;
            this.allloading = true;
            this.allpage++;
            await this._getalllist();
            this.allloading = false;
            // 判断是否全部加载完成
            if (this.alllist.length == this.alltotal) {
                this.allfinished = true;
            }
        },
        // 数据请求方法需要在页面内重写
        async _getalllist() { }
    }
}
// 深拷贝
const _deepClone = (source) => {
    let target;
    if (typeof source === 'object') {
        target = Array.isArray(source) ? [] : {}
        for (let key in source) {
            if (source.hasOwnProperty(key)) {
                if (typeof source[key] !== 'object') {
                    target[key] = source[key]
                } else {
                    target[key] = _deepClone(source[key])
                }
            }
        }
    } else {
        target = source
    }
    return target
};
